<!-- 家长信息 -->
<template>
  <el-card>
    <template #header>
      <div>
        <span>家长信息</span>
      </div>
    </template>

    <!-- 家长信息 -->
    <el-table :data="familyList" style="width: 100%">
      <el-table-column label="姓名" align="center">
        <template #default="{ row }"> {{ row.studentNames }} 家长 </template>
      </el-table-column>
      <el-table-column label="身份证号" prop="parentCardId" align="center"></el-table-column>
      <el-table-column label="手机号" prop="phone" align="center"> </el-table-column>
      <el-table-column label="学生" prop="studentNames" align="center"> </el-table-column>
      <el-table-column label="账号密码" align="center">
        <template #default="{ row }">
          <div style="display: flex; align-items: center; justify-content: center; gap: 6px">
            <span>{{ row.passwordVisible ? row.password : "******" }}</span>
            <el-button link type="primary" size="small" @click="togglePasswordVisibility(row)">
              <el-icon><View v-if="!row.passwordVisible" /><Hide v-else /></el-icon>
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right">
        <template #default="{ row }">
          <el-button link plain type="success" @click="lookFamilyInfoId(row)">查看</el-button>
          <el-button link plain type="info" @click="repasswd(row)">重置密码</el-button>
          <el-button link plain type="danger" @click="deleteAccount(row)">删除</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      v-show="total > 0"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>

  <lookFamilyInfo ref="lookFamilyInfoRef"></lookFamilyInfo>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { getFamilyList as getFamilyListApi, resetPassword, deleteFamily } from "@/api/family/index";
import message from "@/composable/ElMessage";
import { ElMessageBox } from "element-plus";
import lookFamilyInfo from "@/views/family/component/lookFamilyInfo.vue";
import { getStudentList } from "@/api/student/index";

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 家长列表
const familyList = reactive<any[]>([]);
const total = ref(0);
//id->名字映射
const studentMap = ref<Record<string, string>>({});
// 获取家长信息
const getFamilyList = async () => {
  familyList.length = 0;
  const { data } = await getFamilyListApi();

  studentMap.value = {};
  // 使用 Promise.all 并行获取所有家长的学生信息
  const promises = data.map(async (parent: any) => {
    try {
      const res = await getStudentList(parent.id); // 获取对应学生信息
      const students = res?.data || [];

      // 将该家长的学生加入全局映射表
      students.forEach((stu: any) => {
        studentMap.value[stu.id] = stu.name;
      });

      // 扩展 parent 对象，添加 studentNames 字段
      const studentIds =
        parent.studentList
          ?.split(",")
          .map((s: string) => s.trim())
          .filter(Boolean) || [];
      const names = studentIds.map((id: string) => studentMap.value[id]).filter(Boolean); // 过滤掉找不到的名字
      parent.studentNames = names.length > 0 ? names.join(", ") : message.error("获取学生姓名失败");
    } catch (err) {
      console.log(`获取家长 ${parent.id} 的学生失败`, err);
      parent.studentNames = "获取失败";
    }
  });

  // 等待所有学生数据加载完成
  await Promise.all(promises);

  familyList.push(...data);
  total.value = data.length;

  // console.log(studentMap);
};

// 查看密码
const togglePasswordVisibility = (row: any) => {
  row.passwordVisible = !row.passwordVisible;
};

// 查看详情
const lookFamilyInfoRef = ref();
const lookFamilyInfoId = (row: any) => {
  lookFamilyInfoRef.value.open(row);
};

// 重置密码
const repasswd = async (row: any) => {
  await resetPassword(row.id).then((res: any) => {
    // console.log(code);

    if (res.code === "200") {
      message.success("重置密码成功");
    } else {
      message.error("重置密码失败");
    }
  });
  getFamilyList();
};

// 删除家长
const deleteAccount = async (row: any) => {
  ElMessageBox.confirm("确定删除该家长信息吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteFamily(row.id).then((res: any) => {
        if (res.code === "200") {
          message.success("删除成功");
          getFamilyList();
        } else {
          message.error("删除失败");
        }
      });
    })
    .catch(() => {
      message.info("取消删除");
    });
};

onMounted(() => {
  getFamilyList();
});

const onSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getFamilyList();
};

const onCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  getFamilyList();
};
</script>

<style lang="scss" scoped></style>
